/**
 * 库存建账 - 主界面
 * 
 * @author PSI
 * @copyright 2015 - present
 * @license GPL v3
 */
PCL.define("PSI.SLN0001.Inventory.InitInventoryMainForm", {
  extend: "PSI.AFX.Form.MainForm",

  /**
   * @overrride
   */
  initComponent() {
    const me = this;

    const modelName = me.buildModelName(me, "InitInv");
    PCL.define(modelName, {
      extend: "PCL.data.Model",
      fields: ["id", "goodsCode", "goodsName", "goodsSpec",
        "goodsCount", "goodsUnit", "goodsMoney",
        "goodsPrice", "initDate"]
    });
    const store = PCL.create("PCL.data.Store", {
      autoLoad: false,
      model: modelName,
      data: [],
      pageSize: 20,
      proxy: {
        type: "ajax",
        actionMethods: {
          read: "POST"
        },
        url: me.URL("SLN0001/InitInventory/initInfoList"),
        reader: {
          root: 'initInfoList',
          totalProperty: 'totalCount'
        }
      },
      listeners: {
        beforeload: {
          fn() {
            const item = me.gridWarehouse.getSelectionModel().getSelection();
            let warehouseId;
            if (item == null || item.length != 1) {
              warehouseId = null;
            }

            warehouseId = item[0].get("id");

            PCL.apply(store.proxy.extraParams, {
              warehouseId,
            });
          },
          scope: me
        },
        load: {
          fn(e, records, successful) {
            if (successful) {
              me.gotoInitInvGridRecord(me._lastId);
            }
          },
          scope: me
        }
      }
    });

    const gridInitInv = PCL.create("PCL.grid.Panel", {
      cls: "PSI-HL",
      header: {
        height: 30,
        title: me.formatGridHeaderTitle("请选择一个仓库")
      },
      viewConfig: {
        enableTextSelection: true
      },
      columnLines: true,
      emptyText: me.toEmptyText("库存账无期初数据"),
      columns: [{
        header: "物料编码",
        dataIndex: "goodsCode",
        menuDisabled: true,
        sortable: false
      }, {
        header: "品名",
        dataIndex: "goodsName",
        menuDisabled: true,
        sortable: false,
        width: 300
      }, {
        header: "规格型号",
        dataIndex: "goodsSpec",
        menuDisabled: true,
        sortable: false,
        width: 200
      }, {
        header: "期初数量",
        dataIndex: "goodsCount",
        menuDisabled: true,
        sortable: false,
        align: "right"
      }, {
        header: "单位",
        dataIndex: "goodsUnit",
        menuDisabled: true,
        sortable: false,
        width: 50
      }, {
        header: "期初金额",
        dataIndex: "goodsMoney",
        menuDisabled: true,
        sortable: false,
        align: "right",
        xtype: "numbercolumn"
      }, {
        header: "期初单价",
        dataIndex: "goodsPrice",
        menuDisabled: true,
        sortable: false,
        align: "right",
        xtype: "numbercolumn"
      }, {
        header: "建账日期",
        dataIndex: "initDate",
        menuDisabled: true,
        sortable: false,
        width: 90
      }],
      store,
    });

    me.gridInitInv = gridInitInv;

    PCL.define("PSIWarehouse", {
      extend: "PCL.data.Model",
      fields: ["id", "code", "name", "inited", "orgName"]
    });

    const gridWarehouse = PCL.create("PCL.grid.Panel", {
      cls: "PSI-FC",
      header: {
        height: 30,
        title: me.formatGridHeaderTitle("仓库")
      },
      tools: [{
        type: "close",
        handler() {
          PCL.getCmp(me.buildId(me, "panelWarehouse")).collapse();
        }
      }],

      viewConfig: {
        enableTextSelection: true
      },
      columnLines: true,
      columns: [{
        header: "仓库编码",
        dataIndex: "code",
        menuDisabled: true,
        sortable: false,
        width: 70
      }, {
        header: "仓库名称",
        dataIndex: "name",
        width: 120,
        menuDisabled: true,
        sortable: false
      }, {
        header: "建账完毕",
        dataIndex: "inited",
        menuDisabled: true,
        sortable: false,
        width: 80,
        renderer(value) {
          return value == 1
            ? "完毕"
            : "<span style='color:red'>未完</span>";
        }
      }, {
        header: "核算组织机构",
        dataIndex: "orgName",
        width: 200,
        menuDisabled: true,
        sortable: false
      }],
      store: PCL.create("PCL.data.Store", {
        model: "PSIWarehouse",
        autoLoad: false,
        data: []
      }),
      listeners: {
        select: {
          fn: me._onWarehouseGridSelect,
          scope: me
        }
      }
    });
    me.gridWarehouse = gridWarehouse;

    PCL.apply(me, {
      tbar: [{
        iconCls: "PSI-tb-new",
        text: "录入建账数据",
        ...PSI.Const.BTN_STYLE,
        scope: me,
        handler: me._onInitInv
      },
      {
        // TODO 功能尚未开发
        text: "电子表格式录入建账数据",
        ...PSI.Const.BTN_STYLE,
        scope: me,
        hidden: true,
        handler: me._onInitInvBySheet
      }, "-", {
        text: "刷新",
        ...PSI.Const.BTN_STYLE,
        scope: me,
        handler() {
          me.focus();
          me.refreshInvGrid();
        }
      }, "-", {
        text: "标记建账完毕",
        ...PSI.Const.BTN_STYLE,
        scope: me,
        handler: me._onFinish
      }, "-", {
        text: "取消建账完毕标记",
        ...PSI.Const.BTN_STYLE,
        scope: me,
        handler: me._onCancel
      }, "-", {
        text: "生成财务总账建账数据",
        ...PSI.Const.BTN_STYLE,
        scope: me,
        handler: me._onGenGlInitData,
        tooltip: me.buildTooltip("业财融合：由库存建账数据自动生成财务总账中的明细分类账建账数据"),
      }, "-", {
        iconCls: "PSI-tb-help",
        text: "指南",
        ...PSI.Const.BTN_STYLE,
        handler() {
          me.focus();
          window.open(me.URL("/Home/Help/index?t=initInv"));
        }
      }, "-", {
        iconCls: "PSI-tb-close",
        text: "关闭",
        ...PSI.Const.BTN_STYLE,
        handler() {
          me.focus();
          me.closeWindow();
        }
      }].concat(me.getPagination()).concat(me.getShortcutCmp()),
      items: [{
        region: "north",
        height: 55,
        border: 0,
        margin: 0,
        bodyPadding: "0 20 0 20",
        html: "<h2 style='color:#595959;display:inline-block;'>库存建账</h2>&nbsp;&nbsp;<span style='color:#8c8c8c'>初始化库存数据</span>",
      }, {
        id: me.buildId(me, "panelWarehouse"),
        region: "west",
        xtype: "panel",
        layout: "fit",
        border: 0,
        width: 400,
        minWidth: 200,
        split: true,
        header: false,
        collapsible: true,
        bodyPadding: "0 0 5 15",
        items: [gridWarehouse]
      }, {
        region: "center",
        xtype: "panel",
        layout: "fit",
        border: 0,
        bodyPadding: "0 20 5 0",
        items: [gridInitInv]
      }]
    });

    me.callParent(arguments);

    me.freshWarehouseGrid();
  },

  /**
   * @private
   */
  getPagination() {
    const me = this;
    const store = me.getMainGrid().getStore();
    const result = ["->", {
      id: "pagingToolbar",
      cls: "PSI-Pagination",
      border: 0,
      xtype: "pagingtoolbar",
      store
    }, "-", {
        xtype: "displayfield",
        fieldStyle: "font-size:13px",
        value: "每页显示"
      }, {
        id: "comboCountPerPage",
        xtype: "combobox",
        cls: "PSI-Pagination",
        editable: false,
        width: 60,
        store: PCL.create("PCL.data.ArrayStore", {
          fields: ["text"],
          data: [["20"], ["50"], ["100"],
          ["300"], ["1000"]]
        }),
        value: 20,
        listeners: {
          change: {
            fn() {
              store.pageSize = PCL.getCmp("comboCountPerPage").getValue();
              store.currentPage = 1;
              PCL.getCmp("pagingToolbar").doRefresh();
            },
            scope: me
          }
        }
      }, {
        xtype: "displayfield",
        fieldStyle: "font-size:13px",
        value: "条建账记录"
      }]

    return result;
  },

  getMainGrid() {
    const me = this;
    return me.gridInitInv;
  },

  /**
   * 快捷访问
   * 
   * @private
   */
  getShortcutCmp() {
    return ["|", " ",
      {
        cls: "PSI-Shortcut-Cmp",
        labelWidth: 0,
        emptyText: "快捷访问",
        xtype: "psi_mainmenushortcutfield",
        width: 90
      }
    ];
  },

  /**
   * @private
   */
  freshWarehouseGrid(id) {
    const me = this;

    const grid = me.gridWarehouse;
    const el = grid.getEl() || PCL.getBody();
    el.mask(PSI.Const.LOADING);
    me.ajax({
      url: me.URL("SLN0001/InitInventory/warehouseList"),
      callback(options, success, response) {
        const store = grid.getStore();

        store.removeAll();

        if (success) {
          const data = me.decodeJSON(response.responseText);
          store.add(data);
          if (id) {
            const r = store.findExact("id", id);
            if (r != -1) {
              grid.getSelectionModel().select(r);
            } else {
              grid.getSelectionModel().select(0);
            }
          } else {
            grid.getSelectionModel().select(0);
          }
        }

        el.unmask();
      }
    });
  },

  /**
   * @private
   */
  _onWarehouseGridSelect() {
    const me = this;

    me.refreshInvGrid();
  },

  /**
   * @private
   */
  refreshInvGrid(id) {
    const me = this;
    const grid = me.gridInitInv;
    const item = me.gridWarehouse.getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      grid.setTitle(me.formatGridHeaderTitle("请选一个仓库"));
      return;
    }

    const warehouse = item[0];
    grid.setTitle(me.formatGridHeaderTitle("仓库: " + warehouse.get("name")));

    me._lastId = id;
    PCL.getCmp("pagingToolbar").doRefresh()
  },

  /**
   * @private
   */
  _onInitInv() {
    const me = this;

    const item = this.gridWarehouse.getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("请选择要建账的仓库");
      return;
    }
    const warehouse = item[0];

    if (warehouse.get("inited") == 1) {
      me.showInfo(`仓库 <span style='color:red'>${warehouse.get("name")}</span> 已经建账完毕，不能再录入建账数据`);
      return;
    }

    const form = PCL.create("PSI.SLN0001.Inventory.InitInventoryEditForm", {
      warehouse,
      parentForm: me,
    });
    form.show();
  },

  /**
   * TODO 通过电子表格录入建账数据
   * 
   * @private
   */
  _onInitInvBySheet() {
    const me = this;
    const item = me.gridWarehouse.getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("请选择要建账的仓库");
      return;
    }
    const warehouse = item[0];

    if (warehouse.get("inited") == 1) {
      me.showInfo(`仓库[${warehouse.get("name")}]已经建账完毕`);
      return;
    }

    me.showInfo("TODO")
  },

  /**
   * @private
   */
  _onFinish() {
    const me = this;
    const item = this.gridWarehouse.getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("请选择要标记的仓库");
      return;
    }
    const warehouse = item[0];
    if (warehouse.get("inited") == 1) {
      me.showInfo(`仓库 <span style='color:red'>${warehouse.get("name")}</span> 已经标记建账完毕`);
      return;
    }

    me.confirm(`请确认是否给仓库 <span style='color:red'>${warehouse.get("name")}</span> 标记建账完毕?`,
      () => {
        const el = PCL.getBody();
        el.mask(PSI.Const.SAVING);
        me.ajax({
          url: me.URL("SLN0001/InitInventory/finish"),
          params: {
            warehouseId: warehouse.get("id")
          },
          callback(options, success, response) {
            el.unmask();
            if (success) {
              const data = me.decodeJSON(response.responseText);
              if (data.success) {
                me.showInfo("成功标记建账完毕");
                me.freshWarehouseGrid(warehouse.get("id"));
              } else {
                me.showInfo(data.msg);
              }
            } else {
              me.showInfo("网络错误");
            }
          }
        });
      });
  },

  /**
   * @private
   */
  _onCancel() {
    const me = this;
    const item = this.gridWarehouse.getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("请选择要取消建账的仓库");
      return;
    }
    const warehouse = item[0];

    if (warehouse.get("inited") == 0) {
      me.showInfo(`仓库 <span style='color:red'>${warehouse.get("name")}</span> 没有标记建账完毕`);
      return;
    }

    me.confirm(`请确认是否取消仓库 <span style='color:red'>${warehouse.get("name")}</span> 的建账完毕标志?`,
      () => {
        const el = PCL.getBody();
        el.mask(PSI.Const.SAVING);
        me.ajax({
          url: me.URL("SLN0001/InitInventory/cancel"),
          params: {
            warehouseId: warehouse.get("id")
          },
          callback(options, success, response) {
            el.unmask();
            if (success) {
              const data = me.decodeJSON(response.responseText);
              if (data.success) {
                me.showInfo("成功取消建账标志");
                me.freshWarehouseGrid(warehouse.get("id"));
              } else {
                me.showInfo(data.msg);
              }
            } else {
              me.showInfo("网络错误");
            }
          }
        });
      });
  },

  /**
   * @private
   */
  gotoInitInvGridRecord(id) {
    const me = this;
    const grid = me.gridInitInv;
    const store = grid.getStore();
    if (id) {
      const r = store.findExact("id", id);
      if (r != -1) {
        grid.getSelectionModel().select(r);
      } else {
        grid.getSelectionModel().select(0);
      }
    } else {
      grid.getSelectionModel().select(0);
    }
  },

  /**
   * @private
   */
  _onGenGlInitData() {
    const me = this;
    const item = this.gridWarehouse.getSelectionModel().getSelection();
    if (item == null || item.length != 1) {
      me.showInfo("请选择仓库");
      return;
    }
    const warehouse = item[0];

    if (warehouse.get("inited") == 0) {
      me.showInfo(`仓库 <span style='color:red'>${warehouse.get("name")}</span> 还没有建账完毕`);
      return;
    }

    me.confirm(`请确认是否生成仓库 <span style='color:red'>${warehouse.get("name")}</span> 的总账建账数据?`,
      () => {
        const el = PCL.getBody();
        el.mask(PSI.Const.SAVING);
        me.ajax({
          url: me.URL("SLN0001/InitInventory/genGlInitData"),
          params: {
            id: warehouse.get("id")
          },
          callback(options, success, response) {
            el.unmask();
            if (success) {
              const data = me.decodeJSON(response.responseText);
              if (data.success) {
                me.showInfo("成功生成总账建账数据");
              } else {
                me.showInfo(data.msg);
              }
            } else {
              me.showInfo("网络错误");
            }
          }
        });
      });
  }
});
